package cn.wk.userdetail;

import cn.wk.client.UserContextClient;
import cn.wk.domain.LoginUser;
import cn.wk.domain.Permission;
import cn.wk.mapper.LoginUserMapper;
import cn.wk.mapper.PermissionMapper;
import cn.wk.util.AjaxResult;
import cn.wk.vo.UserContext;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MyUserDetail implements UserDetailsService {
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private UserContextClient userContextClient;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据中查询用户
        LoginUser loginUser = loginUserMapper.selectByUsername(username);
        //准备权限  从数据库中查询
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(loginUser.getId());
        permissions.forEach(permission -> {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission.getSn());
            authorities.add(simpleGrantedAuthority);
        });

        String context = null;
        //判断类型为门户还是后台
        if(loginUser.getType().intValue() == loginUser.TYPE_ADMIN){
            //通过用户id去查询其他的部门信息等
            AjaxResult ajaxResult = userContextClient.selectLogin(loginUser.getId());
            context = ajaxResult.getResultObj().toString();
        }else {
            UserContext userContext = new UserContext();
            userContext.setUser_id(loginUser.getId());
            userContext.setUser_name(loginUser.getUsername());
            context = JSON.toJSONString(userContext);
            System.out.println("-----门户------");
            System.out.println(context);
        }
        User user = new User(context, loginUser.getPassword(), loginUser.isEnabled()
                , loginUser.isAccountNonExpired(), loginUser.isCredentialsNonExpired()
                , loginUser.isAccountNonLocked(), authorities);
        return user;
    }

}
